"""
    Author:
    Date: 2018-10-26

    微信管理后台的首页
"""
import random

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.urls import reverse

from entities import sms_mgr

from utils import ajax
from utils import util
from utils import wx_util

from .. import helpers
from .. helpers import gma_login_required


def handler400(request, exception, template_name="400.html"):
    """ 自己的400页面 """
    context = {
        'csrf_token': ''
    }
    response = render_to_response("gma/400.html", context)
    response.status_code = 400
    return response


def handler403(request, exception, template_name="403.html"):
    """ 自己的403页面 """
    context = {
        'csrf_token': ''
    }
    response = render_to_response("gma/403.html", context)
    response.status_code = 403
    return response


def handler404(request, exception, template_name="404.html"):
    """ 自己的404页面 """
    context = {
        'csrf_token': ''
    }
    response = render_to_response("gma/404.html", context)
    response.status_code = 404
    return response


def handler500(request, template_name="500.html"):
    """ 自己的500页面
        参考： https://docs.djangoproject.com/en/2.0/ref/views/#the-500-server-error-view
    """
    context = {
        'csrf_token': ''
    }
    response = render_to_response("gma/500.html", context)
    response.status_code = 500
    return response


def login(request):
    """ 如果用户没有登录，则进入登录界面 """
    gm = helpers.get_request_gm(request)
    if gm is not None:
        redirect_url = reverse('gma:home')
        return HttpResponseRedirect(redirect_url)

    context = helpers.build_context(request)
    return render(request, 'gma/login.html', context)


def fetch_smscode(request):
    """ 获取验证码 """
    mobile = request.POST['mobile'].strip()
    if not mobile:
        return ajax.error_response('手机号码不可以为空!')

    sms_code = ''.join([random.choice('0123456789') for _ in range(4)])
    success = sms_mgr.send_sms_code(mobile, sms_code)
    if not success:
        return ajax.error_response('验证码发送失败!')

    return ajax.success_response({}, '验证码已发送')


@gma_login_required
def index(request):
    """ 微信管理后台的首页 """
    wx_util.save_wx_code(request)

    today_begin_time, today_end_time = util.get_today_interval()

    context = helpers.build_context(request)
    context['gm_name'] = helpers.get_request_gm_name(request)
    context['begin_time'] = today_begin_time
    context['end_time'] = today_end_time
    return render(request, 'gma/homepage.html', context)


def gallery(request, image):
    """ test页面 """
    context = helpers.build_context(request)
    context['image_url'] = image
    context['is_svga'] = image.lower().endswith('.svga')
    return render(request, 'gma/gallery.html', context)


if __name__ == '__main__':
    print('ok')
